//
//  MUserAccountViewModel.swift
//  iOSweibo
//
//  Created by lzm on 16/5/14.
//  Copyright © 2016年 lzm. All rights reserved.
//

import UIKit

class MUserAccountViewModel: NSObject {
    
    //单例
    static let sharedInstance : MUserAccountViewModel = MUserAccountViewModel()
    //解档账户
    let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
    
    //账号拿到单例
    var userAccount : MUserAccount?
    
    override init() {
        super.init()
        userAccount = loadUserAccount()
        
}

    //判断用户是否登录
    var isUserLogin : Bool{
        get{
            return userAccount != nil
        }
    }

    //发送POST请求获得AccseeToken
    func loadAccessToken(code:String, callback:(error : NSError?) -> ()){
        let tokenstr = "oauth2/access_token"
        //token参数
        let parameters = [
            "client_id" : client_id,
            "client_secret": "3aac4ec4d8870280bae691c541bb03f4",
            "grant_type": "authorization_code" ,
            "code" : code,
            "redirect_uri": redirect_uri
        ]
        //发送请求
        MNetworkTool.sharedInstance.request(RequestMethod.POST, URLString: tokenstr, parameters: parameters, success: { (task , responseObject) -> Void in
//            MPrint(items: "获取response成功:\(responseObject)")
            //判断字典转模型是否正确
            if let result = responseObject
            {
                //字典转模型
                let userAccount = MUserAccount(dict: result as! [String : AnyObject])
//                MPrint(items: "userAccount:\(userAccount)")
                
                //将账户赋值给属性
                self.userAccount = userAccount
                //调用归档方法,将模型归档到沙河
                //NSKeyedArchiver.archiveRootObject(userAccount, toFile: self.accountPath)
                self.saveUserInfo()
                
                
               
                callback(error: nil)
            }
            else
            {
                MPrint(items: "字典转模型失败~")
            }
            
            }, failure: { (task, error) -> Void in
//                MPrint(items: "获取失败:\(error)")
                callback(error: error)
        })
    }
    
    //将用户信息保存到沙河中
    private func saveUserInfo()
    {
        if let account = userAccount{
            NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
        }
    }
    
    func loadUserAccount() -> MUserAccount?
    {
        if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(self.accountPath) as? MUserAccount
        {
            
            if userAccount.expiresDare?.compare(NSDate()) != NSComparisonResult.OrderedAscending
            {
//                MPrint(items: "\(self.accountPath)")
                MPrint(items: "没有过期")
                return userAccount
            }
            else
            {
                return nil
            }
            
        }
        else
        {
            //没有加载到账户
            return nil
        }
        
    }
    
    
    
    //MARK: 获取用户请求
    func loadUserInfo(loadUserCallBack:() ->()){
        //可选绑定会造成嵌套层次很多,swift提供了一种形式,防卫: guard
        guard let access_token = userAccount?.access_token else
        {
            return
        }
        
        guard let uid = userAccount?.uid else
        {
            MPrint(items: "uid没有值")
            return
        }
        
        //获取用户URL
        let urlStr = "2/users/show.json"
        
        //参数
        let parameters = ["access_token": access_token, "uid" : uid]
        
        MPrint(items: "access_token:\(access_token)")
        
        MNetworkTool.sharedInstance.request(RequestMethod.GET, URLString: urlStr, parameters: parameters, success: { (_, responseObject) -> Void in
//            MPrint(items: "获取用户信息\(responseObject)")
            if let result = responseObject as? [String : AnyObject]{
                let screen_name = result["screen_name"] as? String
                let avatar_large = result["avatar_large"] as? String
                self.userAccount?.screen_name = screen_name
                self.userAccount?.avatar_large = avatar_large
                self.saveUserInfo()
                
                loadUserCallBack()
                
            }
            }) { (_, error) -> Void in
                MPrint(items: "获取用户信息失败!")
                
        }
    }

}
